package com.example.livebroadcast.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.livebroadcast.model.UserRedis;
import com.example.livebroadcast.service.LiveService;
import com.example.livebroadcast.service.UserService;

@RestController
public class LoginController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;
	
	@Autowired
	private LiveService liveService;

	@RequestMapping(value = "/login")
	public ModelAndView toLogin(ModelMap modelMap) {
		modelMap.addAttribute("user", new UserRedis());
		modelMap.addAttribute("errorMessage", "");
		return new ModelAndView("user/login");
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView doLogin(@ModelAttribute(value = "user") UserRedis userRedis, ModelMap modelMap,
			HttpSession session) {
		String url = "user/liveList";
		if (userService.isUser(userRedis)) {
			session.setAttribute("user", userRedis);
			modelMap.addAttribute("liveList", liveService.getAll());
		} else {
			modelMap.addAttribute("user", userRedis);
			modelMap.addAttribute("errorMessage", "用户名或密码出错");
			logger.info("用户名="+ userRedis.getName());
			url = "user/login";
		}
		return new ModelAndView(url);
	}
	
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpSession session) {
		session.invalidate();
		return new ModelAndView("login");
	}
}
